// 获取画布和上下文
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');

// 游戏配置
const gridSize = 20;
const tileCount = canvas.width / gridSize;
let speed = 7;

// 蛇的初始位置和速度
let snake = [
    { x: 10, y: 10 }
];
let dx = 1;
let dy = 0;

// 食物类型
const foodTypes = {
    normal: { color: 'red', points: 10 },
    special: { color: 'gold', points: 30 },
    super: { color: 'purple', points: 50 }
};

// 食物位置和类型
let food = {
    x: Math.floor(Math.random() * tileCount),
    y: Math.floor(Math.random() * tileCount),
    type: 'normal'
};

// 障碍物
let obstacles = [];
const obstacleCount = 5;

// 游戏状态
let score = 0;
let highScore = localStorage.getItem('snakeHighScore') || 0;
let gameOver = false;

// 检查位置是否被占用，允许传入额外的安全区
function isPositionOccupied(pos, extraSafeZones = []) {
    // 检查是否与蛇重叠
    for (let segment of snake) {
        if (segment.x === pos.x && segment.y === pos.y) return true;
    }
    // 检查是否与食物重叠
    if (food.x === pos.x && food.y === pos.y) return true;
    // 检查是否与障碍物重叠
    for (let obstacle of obstacles) {
        if (obstacle.x === pos.x && obstacle.y === pos.y) return true;
    }
    // 检查是否在额外安全区
    for (let safe of extraSafeZones) {
        if (safe.x === pos.x && safe.y === pos.y) return true;
    }
    return false;
}

// 游戏主循环
function gameLoop() {
    if (gameOver) return;
    
    setTimeout(function() {
        requestAnimationFrame(gameLoop);
    }, 1000 / speed);
    
    update();
    draw();
}

// 更新游戏状态
function update() {
    // 移动蛇
    const head = { x: snake[0].x + dx, y: snake[0].y + dy };
    
    // 检查是否撞墙
    if (head.x < 0 || head.x >= tileCount || head.y < 0 || head.y >= tileCount) {
        endGame();
        return;
    }
    
    // 检查是否撞到自己
    for (let i = 0; i < snake.length; i++) {
        if (head.x === snake[i].x && head.y === snake[i].y) {
            endGame();
            return;
        }
    }
    
    // 检查是否撞到障碍物
    for (let obstacle of obstacles) {
        if (head.x === obstacle.x && head.y === obstacle.y) {
            endGame();
            return;
        }
    }
    
    snake.unshift(head);
    
    // 检查是否吃到食物
    if (head.x === food.x && head.y === food.y) {
        score += foodTypes[food.type].points;
        document.getElementById('score').textContent = score;
        generateFood();
        // 每得100分增加速度
        if (score % 100 === 0) {
            speed += 1;
        }
    } else {
        snake.pop();
    }
}

// 绘制游戏画面
function draw() {
    // 清空画布
    ctx.fillStyle = 'white';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    // 绘制障碍物
    ctx.fillStyle = '#666';
    obstacles.forEach(obstacle => {
        ctx.fillRect(obstacle.x * gridSize, obstacle.y * gridSize, gridSize - 2, gridSize - 2);
    });
    
    // 绘制蛇
    ctx.fillStyle = 'green';
    snake.forEach(segment => {
        ctx.fillRect(segment.x * gridSize, segment.y * gridSize, gridSize - 2, gridSize - 2);
    });
    
    // 绘制食物
    ctx.fillStyle = foodTypes[food.type].color;
    ctx.fillRect(food.x * gridSize, food.y * gridSize, gridSize - 2, gridSize - 2);
}

// 初始化障碍物，避开蛇头和前进方向一格
function initObstacles() {
    obstacles = [];
    // 蛇头和前进方向一格
    const head = snake[0];
    const next = { x: head.x + dx, y: head.y + dy };
    const safeZones = [head, next];
    for (let i = 0; i < obstacleCount; i++) {
        let obstacle;
        do {
            obstacle = {
                x: Math.floor(Math.random() * tileCount),
                y: Math.floor(Math.random() * tileCount)
            };
        } while (isPositionOccupied(obstacle, safeZones));
        obstacles.push(obstacle);
    }
}

// 生成新的食物，避开蛇头和前进方向一格
function generateFood() {
    let newFood;
    // 蛇头和前进方向一格
    const head = snake[0];
    const next = { x: head.x + dx, y: head.y + dy };
    const safeZones = [head, next];
    do {
        newFood = {
            x: Math.floor(Math.random() * tileCount),
            y: Math.floor(Math.random() * tileCount),
            type: getRandomFoodType()
        };
    } while (isPositionOccupied(newFood, safeZones));
    food = newFood;
}

// 随机生成食物类型
function getRandomFoodType() {
    const rand = Math.random();
    if (rand < 0.7) return 'normal';    // 70% 概率普通食物
    if (rand < 0.9) return 'special';   // 20% 概率特殊食物
    return 'super';                      // 10% 概率超级食物
}

// 游戏结束
function endGame() {
    gameOver = true;
    if (score > highScore) {
        highScore = score;
        localStorage.setItem('snakeHighScore', highScore);
    }
    document.getElementById('gameOver').style.display = 'block';
    document.getElementById('finalScore').textContent = score;
    document.getElementById('highScoreModal').textContent = highScore;
}

// 重新开始游戏
function restartGame() {
    snake = [{ x: 10, y: 10 }];
    dx = 1;
    dy = 0;
    score = 0;
    speed = 7;
    gameOver = false;
    document.getElementById('score').textContent = '0';
    document.getElementById('gameOver').style.display = 'none';
    document.getElementById('highScore').textContent = highScore;
    initObstacles();
    generateFood();
    gameLoop();
}

// 键盘控制
document.addEventListener('keydown', function(event) {
    switch(event.key) {
        case 'ArrowUp':
            if (dy !== 1) {
                dx = 0;
                dy = -1;
            }
            break;
        case 'ArrowDown':
            if (dy !== -1) {
                dx = 0;
                dy = 1;
            }
            break;
        case 'ArrowLeft':
            if (dx !== 1) {
                dx = -1;
                dy = 0;
            }
            break;
        case 'ArrowRight':
            if (dx !== -1) {
                dx = 1;
                dy = 0;
            }
            break;
    }
});

// 开始游戏
initObstacles();
gameLoop(); 